const express = require('express');

const router = express.Router();

const articleModel = require('../model/articleModel');

const commentModel = require('../model/commentModel');

//渲染info
router.get('/info/:articleId', (req, res) => {
    let articleId = req.params.articleId;
   
    articleModel.findById(articleId).populate('user', 'username avatar').exec((err, articles) => {
        if (err) {
            console.log(err);
        } else {
           
            commentModel.find({
                article: articleId
            }).populate('user', 'username avatar').exec((err, comments) => {
                if (err) {
                    console.log(err);
                } else {
                    res.render('info', {
                        articles,
                        comments
                    });
                }
            });
        }
    });
});
router.post('/addComment', (req, res) => {
    console.log(req.body);
    let comment = new commentModel({
        comment: req.body.comment,
        user: req.body.userId,
        article: req.body.articleId
    });
    comment.save((err, info) => {
        if (err) {
            console.log(err);
            res.send("评论失败");
        } else {
            // res.send('ok');
            res.redirect('/comment/info/' + req.body.articleId)
        }
    });

});

module.exports = router;